#include<iostream>
#include<cstdlib>
#include<unistd.h>
#include<string.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

void Write(int wfd){
    const char* msg="I'm a father";
    int cnt=5;
    while(cnt){
        write(wfd,msg,strlen(msg));
        --cnt;
        sleep(1);
    }
    close(wfd);//解释这里为什么要关闭
}
void Read(int rfd){
    char buffer[1024]={0};
    while(true){
        ssize_t n=read(rfd,buffer,sizeof(buffer));
        if(n>0){
            buffer[n]='\0';
            cout<<buffer<<endl;
        }else if(n==0){
            cout<<"end of file"<<endl;
            break;
        }else{
            perror("read");
            break;
        }
    }
}
int main(){
    //创建通信管道
    int pipefd[2]={0};
    int n=pipe(pipefd);
    if(n<0){
        perror("pipe");
        return 1;
    }
    
    //开始通信，子进程读，父进程写
    pid_t id=fork();
    if(id==0){
        //child
        close(pipefd[1]);
        Read(pipefd[0]);
        exit(0);
    }else if(id>0){
        //father
        close(pipefd[0]);
        Write(pipefd[1]);
        pid_t ret=waitpid(id,nullptr,0);
        if(ret>0){
            cout<<"wait successfully!"<<endl;
        }else if(ret<0){
            cout<<"wait failed"<<endl;
            return 2;
        }
    }
    return 0;
}